package concurrent;

/**
 * @File Info: leetcode -- <PrintNumInTurn>
 * @Author: 18362
 * @Create: 2022-03-14 13:28:22 星期一
 */

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 两个线程交替打印数字，从1打印到74
 * 比如线程A打印0 1 2 3 4，然后线程B打印 5 6 7 8 9，然后A再打印。。。
 */
public class PrintNumInTurn {

    public static ReentrantLock lock = new ReentrantLock();
    public static Condition condition = lock.newCondition();
    public static volatile int cnt = 0;
    public static volatile int threshold = 75;
    public static volatile boolean flag = false;

    static class MyTask implements Runnable {

        public boolean f;
        public String name;

        public MyTask(String name, boolean f) {
            this.name = name;
            this.f = f;
        }

        @Override
        public void run() {
            while (true) {
                lock.lock();
                try {
                    while (cnt < threshold && flag != f)
                        condition.await();
                    flag = !flag;
                    if (cnt >= threshold) {
                        condition.signalAll();
                        break;
                    }
                    for (int i = 0; i < 5 && cnt <= threshold; i++) {
                        System.out.println(name + ":" + cnt);
                        cnt++;
                    }
                    condition.signalAll();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    /*
    public static Object monitor = new Object();
    public static volatile int cnt = 0;
    public static volatile boolean flag = false;

    static class MyThread extends Thread {

        private boolean f;

        public MyThread(String name, boolean f) {
            super(name);
            this.f = f;
        }

        public void run() {
            synchronized (monitor) {
                try {
                    while (true) {
                        while (cnt < 75 && flag != f) {
                            monitor.wait();
                        }

                        flag = !flag;

                        if (cnt >= 75) {
                            monitor.notifyAll();
                            break;
                        }

                        for(int i=0; i<5 && cnt < 75; ++i) {
                            System.out.println(getName() + ": " + cnt);
                            cnt++;
                        }
                        monitor.notifyAll();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        new MyThread("thread-1", false).start();
        new MyThread("thread-2", true).start();
    }*/
}
